package com.mililoan.console.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mililoan.common.constant.RightmrgGlobe;
import com.mililoan.common.exception.SessionTimeoutException;
import com.mililoan.console.service.OnlineService;
import com.mililoan.model.system.User;


/**
 * 
 * @ClassName: LoginInterceptor
 * @Description: springmvc 登录校验
 * @author YangChaofeng 2016年5月3日 上午10:14:30
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger	LOGGER	= LoggerFactory.getLogger(LoginInterceptor.class);
	// 不需要拦截的url
	private List<String>		exceptUrls;

	@Override
	public void afterCompletion(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse,
			Object obj, Exception exception) throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse,
			Object handler, ModelAndView modelandview) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		LOGGER.debug(" login check begin...........");
		String requestUri = request.getRequestURI();
		for (String url : exceptUrls) {
			if (requestUri.endsWith(url)) {
				return true;
			}
		}
		HttpSession session = request.getSession();
		Object userObj = session.getAttribute(RightmrgGlobe.SESSION_USER_KEY);
		if (null == userObj) {
				LOGGER.debug(" session Timeout login check end...........");
			throw new SessionTimeoutException("session超时");
		} else {
			User user = (User) userObj;
			OnlineService.updateTouchDate(user.getId());
			boolean checkLogin = OnlineService.checkCurrLogin(user.getId(), request.getSession().getId());
			if (checkLogin == false) {
				session.removeAttribute(RightmrgGlobe.SESSION_USER_KEY);
				session.removeAttribute(RightmrgGlobe.SESSION_USER_FUNS);
				session.removeAttribute(RightmrgGlobe.SESSION_DEP_MODULES);
				session.invalidate();
				throw new SessionTimeoutException("session非当前用户");
			}
				LOGGER.debug(" login check end...........");
			return true;
		}
	}

	/**
	 * 获取 exceptUrls
	 * 
	 * @return exceptUrls
	 */
	public List<String> getExceptUrls() {
		return exceptUrls;
	}

	/**
	 * 设置 exceptUrls
	 * 
	 * @param exceptUrls
	 *            对exceptUrls进行赋值
	 */
	public void setExceptUrls(List<String> exceptUrls) {
		this.exceptUrls = exceptUrls;
	}
}
